package apidoc

import (
	"reflect"
	"github.com/gin-gonic/gin"
)

var inited = 0

func Register(app *gin.Engine, process interface{}, request reflect.Type, response reflect.Type, args ...string) Document {
	if inited == 0 {
		inited = 1
		var path = "cgidoc"
		app.GET(path, cgidoc)
		app.POST(path, cgidoc)

		path = "getcgilist"
		app.GET(path, getcgilist)
		app.POST(path, getcgilist)

		path = "getcgidoclist"
		app.GET(path, getcgidoclist)
		app.POST(path, getcgidoclist)
	}

	if len(args) == 0 {
		args = []string{request.PkgPath()}
	} else if args[0] == "${package}" {
		args[0] = request.PkgPath()
	}

	proc := reflect.ValueOf(process)
	callback := func(ctx *gin.Context) {
		req := reflect.New(request).Interface()
		rsp := reflect.New(response).Interface()
		err := ctx.ShouldBind(req)
		if err == nil {
			proc.Call([]reflect.Value{reflect.ValueOf(req), reflect.ValueOf(rsp)})
			ctx.JSON(200, rsp)
		} else {
			panic(err)
		}
	}

	app.GET(args[0], callback)
	app.POST(args[0], callback)

	return AddDocument(request, response, args...)
}